#include <zenox/localization.hpp>
#include <zenox/home.hpp>
#include <zenox/unicode.hpp>
#include <fstream>
#include <cstdlib>

namespace zenox {

void LocalizationEngine::load_from_file(std::string path) {
    std::ifstream file(u8path(path));
    if (!file) return;
    std::string line;
    while (std::getline(file, line, '\n')) {
        std::size_t index = line.find('@');
        if (index != line.npos) {
            auto k = line.substr(0, index);
            auto v = line.substr(index + 1);
            dict.emplace(*keys.insert(std::move(k)), *vals.insert(std::move(v)));
        }
    }
}

LocalizationEngine &LocalizationEngine::instance() {
    static LocalizationEngine instance = [] () -> LocalizationEngine {
        LocalizationEngine instance;
        if (auto path = std::getenv("ZENO_LOCALIZATION_FILE")) {
            instance.load_from_file(path);
        } else {
            instance.load_from_file(zeno_home_relative("assets/cn.txt"));
        }
        return instance;
    } ();
    return instance;
}

}
